package com.Spring.SpringSpms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.Spring.SpringSpms.model.Priority;


public class PriorityDAOImpl implements PriorityDAO {

	
	private JdbcTemplate jdbcTemplate;
	
	public PriorityDAOImpl(DataSource dataSource) {
		// TODO Auto-generated constructor stub
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public List<Priority> list() {
		
	

		String sql = "SELECT * FROM priority";
		List<Priority> listPriority = jdbcTemplate.query(sql, new RowMapper<Priority>() {

			@Override
			public Priority mapRow(ResultSet rs, int rowNum) throws SQLException {
				Priority aPriority = new Priority();
	
				aPriority.setPriority_id(rs.getInt("priority_id"));
				aPriority.setPriority_name(rs.getString("priority_name"));
	
			return aPriority;
			}
		});
		return listPriority;

}

	@Override
	public void saveOrUpdate(Priority s) {
		// TODO Auto-generated method stub
		
		
		
		if (s.getPriority_id() > 0) {
			// update
			String sql = "UPDATE priority SET priority_name=? WHERE priority_id=?";
			jdbcTemplate.update(sql, s.getPriority_name());
		} else {
			// insert
			String sql = "INSERT INTO priority (priority_name)"
						+ " VALUES (?)";
			jdbcTemplate.update(sql, s.getPriority_name());
			}

	}

	@Override
	public void delete(int priorityId) {
		// TODO Auto-generated method stub
		
		

		String sql = "DELETE FROM priority WHERE priority_id=?";
		jdbcTemplate.update(sql, priorityId);

		
	}

	@Override
	public Priority get(int priorityId) {
		String sql = "SELECT * FROM priority WHERE priority_id=" + priorityId;
		return jdbcTemplate.query(sql, new ResultSetExtractor<Priority>() {

			@Override
			public Priority extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if (rs.next()) {
					Priority s = new Priority();
					s.setPriority_id(rs.getInt("priority_id"));
					s.setPriority_name(rs.getString("priority_name"));
					return s;
				}
				
				return null;
			}
			
		});

}
}